package com.scut.online_black_market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scut.online_black_market.entity.ConsultationListResponse;
import com.scut.online_black_market.dto.ConsultationRequest;
import com.scut.online_black_market.dto.PictureAndName;
import com.scut.online_black_market.entity.Consultation;
import com.scut.online_black_market.entity.Personal;
import com.scut.online_black_market.exception.UniversalException;
import com.scut.online_black_market.mapper.ConsultationListMapper;
import com.scut.online_black_market.dto.ConsultationResponse;
import com.scut.online_black_market.mapper.ConsultationMapper;
import com.scut.online_black_market.mapper.PersonalMapper;
import com.scut.online_black_market.service.ConsultationService;
import com.scut.online_black_market.utility.JwtUtil;
import com.scut.online_black_market.utility.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.time.LocalDateTime;


@Service
public class ConsultationServiceImpl implements ConsultationService {

    @Resource
    private ConsultationMapper consultationMapper;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private HttpServletRequest httpServletRequest;

    @Resource
    private PersonalMapper personalMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ConsultationListMapper consultationListMapper;

    @Override
    public void uploadConsultation(ConsultationRequest consultationRequest) throws UniversalException {

        String studentNumber = jwtUtil.extractStudentNumber(httpServletRequest);

        Personal personal = personalMapper.selectById(studentNumber);

        if (personal == null) throw new UniversalException("该用户不存在");

        float balance = personal.getBalance() - consultationRequest.getConsultationPrice();
        if (balance < 0) {
            throw new UniversalException("余额不足");
        }
        personal.setBalance(balance);

        Consultation consultation = Consultation.builder()
                .consultationTitle(consultationRequest.getConsultationTitle())
                .consultationPrice(consultationRequest.getConsultationPrice())
                .consultationDescription(consultationRequest.getConsultationDescription())
                .question_status(1)
                .proposer(studentNumber)
                .askTime(LocalDateTime.now())
                .build();

        if (consultationMapper.insert(consultation) != 1 || personalMapper.updateById(personal) != 1) {
            throw new UniversalException("发布问题失败，请重试");
        }
    }

    @Override
    /**
     * create by xc at 2020.11.19
     */
    public IPage<ConsultationListResponse> queryConsultationByPage(short pageNo, short pageSize, short typeId) throws UniversalException {
        IPage<ConsultationListResponse> page = new Page<>(pageNo, pageSize);
        QueryWrapper<ConsultationListResponse> wrapper = new QueryWrapper<>();
        wrapper.eq("question_status", 1);

        switch (typeId) {
            case 2:
                wrapper.orderByDesc("consultation_price");
            case 3:
                wrapper.orderByAsc("consultation_price");
            case 4:
                wrapper.orderByDesc("ask_time");
            case 5:
                wrapper.orderByAsc("ask_time");
            default:
        }

        consultationListMapper.selectPage(page, wrapper);
        //将学号插进来
        for (ConsultationListResponse record : page.getRecords()) {
            String studentNumber = record.getProposer();
            if (redisUtil.hasKey(studentNumber)) {
                PictureAndName pictureAndName = (PictureAndName) (redisUtil.get(studentNumber));
                record.setPictureUrl(pictureAndName.getPictureUrl());
                record.setNickname(pictureAndName.getNickname());
            } else {
                throw new UniversalException("consultation proposer not found");
            }
        }
        return page;
    }

    @Override
    public ConsultationResponse queryByConsultationId(BigInteger consultationId) throws UniversalException {

        Consultation consultation=consultationMapper.selectById(consultationId);

        if(consultation==null){
            throw new UniversalException("该问题不存在");
        }

        ConsultationResponse consultationResponse=ConsultationResponse.builder()
                .consultationDescription(consultation.getConsultationDescription())
                .build();

        return consultationResponse;
    }
    @Override
    public void deleteByConsultationId(BigInteger consultationId) throws UniversalException{
        String studentNumber = jwtUtil.extractStudentNumber(httpServletRequest);

        Personal personal = personalMapper.selectById(studentNumber);

        Consultation consultation = consultationMapper.selectById(consultationId);

        personal.setBalance(personal.getBalance() + consultation.getConsultationPrice());

        if(consultation == null)
            throw  new UniversalException("该问题不存在");
        if(!studentNumber.equals(consultation.getProposer()))
            throw new UniversalException("删除失败");
        consultation.setQuestion_status(0);
        if(consultationMapper.updateById(consultation)!=1 || personalMapper.updateById(personal) != 1)
            throw new UniversalException("删除失败请重试");
    }
}
